/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TFrame.java
 *
 * Created on Mar 26, 2012, 6:27:58 PM
 */
package net.nac.tbot;

import java.awt.AWTEvent;
import java.awt.AWTException;
import java.awt.Color;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.FocusEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.nac.tbot.eltetris.Bot;

/**
 *
 * @author DTIT
 */
public class TFrame extends javax.swing.JFrame {

  private TetrisBattleBoard tboard = null;
  private boolean findingBoard = false;
  private Robot robot = null;

  /** Creates new form TFrame */
  public TFrame() {
    initComponents();
    try {
      robot = new Robot();
    } catch (AWTException ex) {
      Logger.getLogger(TFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
    Toolkit.getDefaultToolkit().addAWTEventListener(new AWTFocusListener(), AWTEvent.MOUSE_EVENT_MASK | AWTEvent.FOCUS_EVENT_MASK);
  }

  /** This method is called from within the constructor to
   * initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is
   * always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tPanel1 = new net.nac.tbot.TPanel();
        findBoardButton = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        tPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        javax.swing.GroupLayout tPanel1Layout = new javax.swing.GroupLayout(tPanel1);
        tPanel1.setLayout(tPanel1Layout);
        tPanel1Layout.setHorizontalGroup(
            tPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 178, Short.MAX_VALUE)
        );
        tPanel1Layout.setVerticalGroup(
            tPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 358, Short.MAX_VALUE)
        );

        findBoardButton.setText("Find Board");
        findBoardButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                findBoardButtonActionPerformed(evt);
            }
        });

        jTextField1.setText("55");
        jTextField1.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextField1FocusLost(evt);
            }
        });

        jLabel1.setText("Key Delay:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(tPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(findBoardButton))
                .addContainerGap(74, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(findBoardButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(tPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

  private void findBoardButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_findBoardButtonActionPerformed
   
    if(findingBoard == false){
      findingBoard = true;
      tboard = null;
      findBoardButton.setText("Click inside board...");
    }
  }//GEN-LAST:event_findBoardButtonActionPerformed

  private void jTextField1FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField1FocusLost
    if(tboard != null){
      tboard.setDelay(Integer.parseInt(jTextField1.getText()));
    }
  }//GEN-LAST:event_jTextField1FocusLost

  
  
  
  /**
   * @param args the command line arguments
   */  
  public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          javax.swing.UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException ex) {
      java.util.logging.Logger.getLogger(TFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
      java.util.logging.Logger.getLogger(TFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
      java.util.logging.Logger.getLogger(TFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(TFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {

      @Override
      public void run() {
        new TFrame().setVisible(true);
      }
    });
  }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton findBoardButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField jTextField1;
    private net.nac.tbot.TPanel tPanel1;
    // End of variables declaration//GEN-END:variables

  private class AWTFocusListener implements AWTEventListener {

    @Override
    public void eventDispatched(AWTEvent event) {
      if (event.getID() == FocusEvent.FOCUS_LAST) {
        if (findingBoard) {
          findBorders();
        }
      }
    }
  }

  private void findBorders() {
    findBoardButton.setText("Finding board");
    Point initialPoint = MouseInfo.getPointerInfo().getLocation();
    int ix = initialPoint.x;
    int iy = initialPoint.y;
    int x = 0;
    int y = 0;
    Color color;
    int blackCount = 0;

    while (ix > 0) {

      color = robot.getPixelColor(ix, iy);

      if (color.equals(Color.BLACK)) {
        blackCount++;
      } else {
        blackCount = 0;
      }
      if (blackCount == 6) {
        x = ix;
        break;
      }
      ix--;
    }

    ix = initialPoint.x;
    iy = initialPoint.y;
    blackCount = 0;
    while (iy > 0) {

      color = robot.getPixelColor(ix, iy);

      if (color.equals(Color.BLACK)) {
        blackCount++;
      } else {
        blackCount = 0;
      }
      if (blackCount == 6) {
        y = iy;
        break;
      }
      iy--;
    }
    findingBoard = false;
    tboard = new TetrisBattleBoard(x + 6, y + 6);
    tboard.setBot(new Bot());
    findBoardButton.setText("Find board");
  }
}
